/*
    client.c
    客户端
*/

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/un.h>
#include <netinet/in.h>

#define NAME "tsever"

int main()
{
    // 1 创建套接字
    int fd = socket(AF_UNIX, SOCK_STREAM, 0);
    // 2.连接
    struct sockaddr_un addr;
    addr.sun_family = AF_UNIX;
    strcpy(addr.sun_path, NAME);
    int ret = connect(fd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret == -1)
    {
        perror("客户端连接失败！\n");
        exit(1);
    }
    // 3.读写
    char buf[128];
    while(1)
    {
        memset(buf, 0, sizeof(buf));
        printf("请输入#");
        fgets(buf, sizeof(buf), stdin);
        //会将换行符读入，然后后面字符串比较就不会相等
        buf[strcspn(buf, "\n")] = '\0';  // 去掉末尾的换行符
        write(fd, buf, sizeof(buf));
        if(strcmp(buf, "bye") == 0)
            break;
    }
    memset(buf, 0, sizeof(buf));
    read(fd, buf, sizeof(buf));
    printf("收到的服务器的内容：：%s\n", buf);

    // 4.关闭连接
    close(fd);
    return 0;
}